package com.jihox.abookpro.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import com.jihox.abookpro.util.MyMap;

public class Spine implements Serializable
{

public static final int UNDEFINED 	= -1;
public static final int UNEDITABLE	= 0;
public static final int EDITABLE		= 1;

public static final float defaultSpine = 27.0f;

ArrayList <SpineStep> spineList = new ArrayList (5);

private int editable = UNDEFINED;

public Spine (int spine)
	{
	this ((float) spine);
	}


public Spine (float spine)
	{
	super ();
	spineList.add (new SpineStep (0, 999999, spine));
	}


public Spine ()
	{
	this (defaultSpine);
	}


protected ArrayList <SpineStep> getSpineList ()
	{
	return spineList ;
	}

public int getSpineWidth (int pages)
	{
	for (int i = 0; i < spineList.size(); i++)
		{
		if (spineList.get(i).isRightSpineWidth(pages))
			return (int) Math.round (spineList.get(i).getSpineWidth());
		}
	return (int) defaultSpine;
	}


public boolean isEditable() {
	boolean result = false;
	if (editable == EDITABLE) {
		result = true;
	} 
	
	return result;
}

public void setEditable(int editable) {
	this.editable = editable;
}

protected void addSpineStep (MyMap map)
	{
	spineList.add (new SpineStep (map));
	}


public boolean equals(Spine otherSpine) {
	boolean result = true;
	result = isEditable() == otherSpine.isEditable();
	Iterator<SpineStep> i = otherSpine.getSpineList().iterator();
	SpineStep otherStep = null;
	for (SpineStep s : spineList) {
		if (i.hasNext()) {
			otherStep = i.next();
		} else {
			break;
		}
		result = s.equals(otherStep);
	}
	return result;
}

public class SpineStep implements Serializable
	{
	int fromPage, toPage;
	float spineWidth;


	public SpineStep (int from, int to, float value)
		{
		fromPage = from;
		toPage = to;
		spineWidth = value;
		}

	public SpineStep (MyMap map)
		{
		fromPage = map.get ("fromPage", 0);//$NON-NLS-1$
		toPage = map.get ("toPage", 999999);//$NON-NLS-1$
		spineWidth = ((Float) map.get ("spineWidth", defaultSpine)).floatValue();//$NON-NLS-1$
		}


	public MyMap writeToMap ()
		{
		MyMap item = new MyMap ();
		item.put ("fromPage", fromPage);//$NON-NLS-1$
		item.put ("toPage", toPage);//$NON-NLS-1$
		item.put ("spineWidth", spineWidth);//$NON-NLS-1$
		return item;
		}

	public float getSpineWidth ()
		{
		return spineWidth;
		}

	public boolean isRightSpineWidth (int page)
		{
		return page >= fromPage && page <= toPage;
		}

	public boolean equals(SpineStep otherSpineStep) {
		return otherSpineStep == null ? false :
					 fromPage ==  otherSpineStep.fromPage &&
					 toPage == otherSpineStep.toPage &&
					 spineWidth == otherSpineStep.spineWidth;
	}

	}
}


